﻿using AmazonMODEL;
using MODEL;
using SysCommon;
using SysCommon.Log;
using SysCommon.WinServices;
using SysController;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace AmazonMWS
{
    public partial class FeedsServices : ServiceBase, IServiceController
    {
        public FeedsServices()
        {
            InitializeComponent();
        } 
        public void Start()
        {
            SysCommon.Log.Log.Write("Feeds Services Statr...");
        }

        #region 2015-11-05 创建发布任务【5min】 - void CreateFeedsInfo_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-05 创建发布任务
        /// </summary> 
        private void CreateFeedsInfo_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            ApiOperationType[] typeArr = { ApiOperationType.Product, ApiOperationType.Relationship, ApiOperationType.Image, ApiOperationType.Price, ApiOperationType.Inventory };
            foreach (var appkey in SystemController.RunAccount)
            {
                foreach (var type in typeArr)
                {
                    List<AdRelease> list = SystemController.GetAdRelease(appkey.AccountInfoID, type);
                    if (list == null)
                        continue;
                    Log.Write(string.Format("{1} 创建 {0} 发布任务",type.ToString(), appkey.AccountInfoName));
                    List<AmazonEnvelopeMessage> lsMsg = null;
                    switch (type)
                    {
                        case ApiOperationType.Relationship:
                            lsMsg = HelperController.AmazonEnvelopeMessageList<Relationship>(list.Select(s => s.ProductRelationshipModel).ToList());
                            break;
                        case ApiOperationType.Price:
                            lsMsg = HelperController.AmazonEnvelopeMessageList<Price>(list.Select(s => s.ProductPriceModel).ToList());
                            break;
                        case ApiOperationType.Image:
                            lsMsg = HelperController.AmazonEnvelopeMessageList<ProductImage>(list.Select(s => s.ProductImageModel).ToList());
                            break;
                        case ApiOperationType.Inventory:
                            lsMsg = HelperController.AmazonEnvelopeMessageList<Inventory>(list.Select(s => s.ProductInventoryModel).ToList());
                            break;
                        default:
                            lsMsg = HelperController.AmazonEnvelopeMessageList<Product>(list.Select(s => s.ProductInfoModel).ToList());
                            break; ;
                    }
                    AmazonEnvelope envelope = HelperController.AmazonEnvelopeObject(appkey.MerchantCode, lsMsg, type.ToAmazonMsgType());
                    FeedsInfo model = new FeedsInfo()
                    {
                        AmazonEnvelope = XmlHelper.ObjectToXmlSerializer(envelope),
                        AdReleaseIdList = string.Join(",", list.Select(s => s.AdReleaseID)),
                        FeedType = type.ToAmazonString(),
                        CreateUser = "CreateFeeds",
                        CreateTime = DateTime.Now,
                        AccountInfoId = appkey.AccountInfoID,
                        FeedProcessingStatus = FeedProcessingStatus.Upload.ToString()
                    };
                    bool IsAgain = true;
                Again: int row = SystemController.AddFeedsInfo(model);
                    if (row < 1)
                    {
                        if (IsAgain)
                        {
                            IsAgain = false;
                            goto Again;
                        }
                        //TODO:
                        continue;
                    }
                    else
                    {
                        List<AdRelease> lsUpdate = new List<AdRelease>();
                        foreach (var ls in list)
                        {
                            ls.UpdateTime = DateTime.Now;
                            ls.UpdateUser = "CreateFeeds";
                            ls.ApiOperationStatus = ApiOperationStatus.Processing.ToString();
                            ls.ApiOperationType = type.ToString();
                            lsUpdate.Add(ls);
                        }
                        bool isAgain = true;
                    AgainOne: int count = SystemController.ModifyAdRelease(lsUpdate);
                        if (row < 1)
                        {
                            if (isAgain)
                            {
                                isAgain = false;
                                goto AgainOne;
                            }
                            //TODO:
                        }
                    }
                }
            }
        }
        #endregion

        #region  2015-11-05 提交任务【15:1/2min】 - void FeedSubmit_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-05 提交任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FeedSubmit_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        { 
            foreach (var appkey in SystemController.RunAccount)
            { 
                List<FeedsInfo> list = SystemController.GetFeedsInfo(appkey.AccountInfoID, FeedProcessingStatus.Upload, 15);
                if (list.Count < 0 || list == null)
                    continue;
                List<FeedsInfo> listRe = new List<FeedsInfo>();
                foreach (var ls in list)
                {
                    Log.Write(string.Format("{1} 提交 {0} 任务  ",ls.FeedType,appkey.AccountInfoName));
                    FeedsInfo model = FeedsController.SubmitFeed(appkey, ls);
                    if (model == null)
                        continue;
                    listRe.Add(model);
                }
                bool IsAgain = true;
            Again: int row = SystemController.ModifyFeedsInfo(listRe);
                if (row < 1)
                {
                    if (IsAgain)
                    {
                        IsAgain = false;
                        goto Again;
                    } 
                    continue;
                } 
            }
        }
        #endregion

        #region 2015-11-05 任务进度【10:1/45s】 - void GetFeedSubmitProcessingStatus_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-05 任务进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetFeedSubmitProcessingStatus_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (var appkey in SystemController.RunAccount)
            { 
                List<FeedsInfo> list = SystemController.GetFeedsInfo(appkey.AccountInfoID, FeedProcessingStatus._SUBMITTED_, 10);
                if (list.Count < 0 || list == null)
                    continue;
                Log.Write(string.Format("获取帐号{0}任务进度  ", appkey.AccountInfoName));
                List<FeedsInfo> ReList = FeedsController.GetFeedSubmissionList(appkey, list);
                if (ReList == null)
                    continue;
                bool IsAgain = true;
            Again: int row = SystemController.ModifyFeedsInfo(ReList);
                if (row < 1)
                {
                    if (IsAgain)
                    {
                        IsAgain = false;
                        goto Again;
                    }
                    //TODO:
                    continue;
                }
            }
        }
        #endregion

        #region 2015-11-05 任务结果【15:1/1min】 - void GetFeedSubmitResult_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-05 任务结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetFeedSubmitResult_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (var appkey in SystemController.RunAccount)
            {
                List<FeedsInfo> list = SystemController.GetFeedsInfo(appkey.AccountInfoID, FeedProcessingStatus._DONE_, 15);
                if (list.Count < 0 || list == null)
                    continue;
                List<FeedsInfo> ReList = new List<FeedsInfo>();
                foreach (var ls in list)
                {
                    Log.Write(string.Format("提交 {0} 任务  ", ls.FeedType));
                    FeedsInfo model = FeedsController.GetFeedSubmissionResult(appkey, ls);
                    model.UpdateTime = DateTime.Now;
                    model.UpdateUser = "GetFeedSubmitResult";
                    model.IsDel = false;
                    model.FeedProcessingStatus = FeedProcessingStatus.Complete.ToString();
                    ReList.Add(model);
                }
                bool IsAgain = true;
            Again: int row = SystemController.ModifyFeedsInfo(ReList);
                if (row < 1)
                {
                    if (IsAgain)
                    {
                        IsAgain = false;
                        goto Again;
                    }
                    //TODO:
                    continue;
                } 
            }
        }
        #endregion

        #region  2015-11-05 解析任务【5min】 + void FeedsInfoAnalyze_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-05 解析任务
        /// </summary> 
        private void FeedsInfoAnalyze_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (var appkey in SystemController.RunAccount)
            {
                List<FeedsInfo> list = SystemController.GetFeedsInfo(appkey.AccountInfoID, FeedProcessingStatus.Complete, 200);
                if (list.Count < 0 || list == null)
                    continue;
                foreach (var ls in list)
                {
                    List<string> idList = ls.AdReleaseIdList.Split(',').ToList();
                    List<AdRelease> lsRelease = SystemController.GetAdRelease(idList);
                    ProcessingReport report = XmlHelper.ObjectToXmlDESerializer<ProcessingReport>(ls.ResultData);
                    List<ProcessingReportResult> errResultList = report.Result.Where(s => s.ResultCode == ProcessingReportResultResultCode.Error).ToList();
                    List<AdRelease> lsUpdate = new List<AdRelease>();
                    foreach (var it in lsRelease)
                    {
                        string type = null;
                        switch ((FeedType)Enum.Parse(typeof(FeedType), ls.FeedType))
                        {
                            case FeedType._POST_PRODUCT_DATA_:
                                type = ApiOperationType.Product.ToString();
                                it.IsUpdateProduct = false;
                                it.IsRelease = false;
                                break;
                            case FeedType._POST_PRODUCT_RELATIONSHIP_DATA_:
                                type = ApiOperationType.Relationship.ToString();
                                it.IsUpdateRelationship = false;
                                break;
                            case FeedType._POST_PRODUCT_IMAGE_DATA_:
                                type = ApiOperationType.Image.ToString();
                                it.IsUpdateImage = false;
                                break;
                            case FeedType._POST_PRODUCT_PRICING_DATA_:
                                type = ApiOperationType.Price.ToString();
                                it.IsUpdatePrice = false;
                                break;
                            case FeedType._POST_INVENTORY_AVAILABILITY_DATA_:
                                type = ApiOperationType.Inventory.ToString();
                                it.IsUpdateInventory = false;
                                break;
                            case FeedType._POST_ORDER_FULFILLMENT_DATA_:

                                break;
                        }
                        List<ProcessingReportResult> result = errResultList.Where(s => s.AdditionalInfo.SKU == it.SKU).ToList();
                        if (result != null)
                        {
                            it.ApiOperationStatus = ApiOperationStatus.Error.ToString();
                            it.IsDel = false;
                            it.ApiOperationRemark += string.Format("{0}:上传失败\r\n{1}", type, string.Join("\r\n", result.Select(s => s.ResultDescription)));
                        }
                        else
                        {
                            if (it.IsUpdateImage == false && it.IsUpdateInventory == false && it.IsUpdatePrice == false && it.IsUpdateProduct == false && it.IsUpdateRelationship == false)
                            {
                                it.ApiOperationStatus = ApiOperationStatus.Complete.ToString();
                                it.ApiOperationRemark += string.Format("{0}:上传完成，处理成功！", type);
                            }
                            else
                            {
                                it.ApiOperationStatus = ApiOperationStatus.Success.ToString();
                            }
                            it.IsDel = false;
                        }
                        it.UpdateUser = "AnalyzeFeeds";
                        it.UpdateTime = DateTime.Now;

                        lsUpdate.Add(it);
                    }
                    bool IsAgain = true;
                Again: int row = SystemController.ModifyAdRelease(lsUpdate);
                    if (row < 1)
                    {
                        if (IsAgain)
                        {
                            IsAgain = false;
                            goto Again;
                        }
                        //TODO:
                        continue;
                    }
                }
            }
        }
        #endregion

        #region 2015-11-05 返回任务处理结果 - void ReturnSubmitResult_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-05 返回任务处理结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReturnSubmitResult_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string [] statusArr = { ApiOperationStatus.Error.ToString(), ApiOperationStatus.Complete.ToString() };
            foreach (var appkey in SystemController.RunAccount)
            {
                List<AdRelease> returnList = SystemController.GetAdRelease(appkey.AccountInfoID, statusArr);




            }
        }
        #endregion 

        
         
    }
}